package work.MrSun.xyq.controller;

/**
 * @Author MrSun
 * @Date 2023/4/16 12:32
 */

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import work.MrSun.xyq.model.XyqComment;
import work.MrSun.xyq.model.XyqCommentReply;
import work.MrSun.xyq.model.XyqUser;
import work.MrSun.xyq.service.XyqCommentReplayService;
import work.MrSun.xyq.service.XyqCommentService;
import work.MrSun.xyq.service.XyqUserService;

/**
 * 删除评论实现层
 */
@RestController
public class DeleteCommentByIdController {
    @Autowired
    private XyqCommentService xyqCommentService;

    @Autowired
    private XyqUserService xyqUserService;

    @Autowired
    private XyqCommentReplayService xyqCommentReplayService;

    /**
     * 删除指定评论以及评论下的所有回复
     *
     * @param userId    用户id
     * @param messageId 信息的id
     * @return
     */
    @Transactional//@Transactional注解表示该方法需要在一个事务中执行
    @PostMapping("/deleteCommentByCommentId/{userId}/{messageId}")
    public Integer deleteCommentByCommentId(@PathVariable Integer userId, @PathVariable Integer messageId) {
        //通过id获取到用户
        XyqUser user = xyqUserService.getById(userId);
        if (user == null) {
            return 400;
        }
        //创建评论的对象
        XyqComment xyqComment = new XyqComment();
        //如果不是管理员
        if (user.getUserIsAdmin() == 2) {
            xyqComment.setCommentId(messageId);
        } else {
            xyqComment.setCommentId(messageId);
            xyqComment.setUserId(userId);
        }
        //执行删除
        xyqCommentService.delete(xyqComment);
        XyqCommentReply xyqCommentReply = new XyqCommentReply();
        xyqCommentReply.setCommentId(messageId);
        //评论回复删除操作
        xyqCommentReplayService.delete(xyqCommentReply);
        return 200;
    }

    /**
     * 根据用户ID和评论ID进行删除对应的id（删除指定评论回复）
     *前提是必须拥有对该评论回复记录的删除权限
     * @param userId
     * @param commentReplyId
     * @return
     */
    @Transactional
    @PostMapping("/deleteCommentReplyByCommentId/{userId}/{commentReplyId}")
    public Integer deleteCommentReplyByCommentId(@PathVariable Integer userId,
                                                 @PathVariable Integer commentReplyId) {
        //获取到用户
        XyqUser user = xyqUserService.getById(userId);
        if (user == null) {
            return 400;
        }
        //创建回复评论的对象
        XyqCommentReply xyqCommentReply = new XyqCommentReply();
        if (user.getUserIsAdmin() == 2) {
            xyqCommentReply.setCommentReplyId(commentReplyId);
        } else {
            xyqCommentReply.setCommentReplyId(commentReplyId);
            xyqCommentReply.setReplayUserId(userId);
        }
        xyqCommentReplayService.delete(xyqCommentReply);
        return 200;
    }
}
